package com.example.list;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.example.utils.MyWebView;
/*Android WebView —— Java 与 JavaScript 交互总结
https://zhuanlan.zhihu.com/p/149985867*/
public class WebViewActivity extends AppCompatActivity {

    private MyWebView myWebView;
    String url1="file:///android_asset/js_java_interaction.html";
    String url2="file:///android_asset/baidu.html";
    String url;
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        myWebView = (MyWebView)findViewById(R.id.myWebview);

        myWebView.getSettings().setAllowFileAccess(true);
        myWebView.getSettings().setAllowFileAccessFromFileURLs(true);

//        myWebview.getSettings().setJavaScriptEnabled(false);
        url=url2;
        myWebView.loadUrl(url);


        myWebView.addJavascriptInterface(this, "main");
        myWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
//        myWebView.setWebViewClient(new WebViewClient(){
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//
//            }
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//
//            }
//        });

    }
    public void javaCallJs(View v){
        myWebView.loadUrl("javascript:javaCallJs(" + "'Message From Java'" + ")");
    }

    @JavascriptInterface
    public void jsCallJava(String message){
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    public void jsFalse(View view) {
        myWebView.setBoolean(false);
        myWebView.loadUrl(url);

    }

    public void jsTrue(View view) {
        myWebView.setBoolean(true);
        myWebView.loadUrl(url);
    }
}